package com.roger.homecenterscreen.voice

import android.util.Log
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * Dify聊天工作流管理器
 */
class DifyManager {
    companion object {
        private const val TAG = "DifyManager"
        private const val TIMEOUT_SECONDS = 30L
    }
    
    private val client = OkHttpClient.Builder()
        .connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
        .readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
        .writeTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
        .build()
    
    /**
     * 流式聊天
     */
    suspend fun streamChat(
        message: String,
        onResponse: (String) -> Unit
    ) = withContext(Dispatchers.IO) {
        try {
            Log.i(TAG, "发送消息到Dify: $message")
            
            // 构建请求体
            val requestBody = JSONObject().apply {
                put("query", message)
                put("response_mode", "streaming")
                put("conversation_id", "")
                put("user", "user")
            }.toString()
            
            // 构建请求
            val request = Request.Builder()
                .url("${VoiceConfig.DIFY_BASE_URL}/chat-messages")
                .post(requestBody.toRequestBody("application/json".toMediaType()))
                .addHeader("Authorization", "Bearer ${VoiceConfig.DIFY_API_KEY}")
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "text/event-stream")
                .build()
            
            // 发送请求
            client.newCall(request).execute().use { response ->
                if (!response.isSuccessful) {
                    throw IOException("请求失败: ${response.code}")
                }
                
                val source = response.body?.source() ?: throw IOException("响应体为空")
                val fullResponse = StringBuilder()
                
                try {
                    while (!source.exhausted()) {
                        val line = source.readUtf8Line() ?: break
                        
                        if (line.startsWith("data: ")) {
                            val data = line.substring(6).trim()
                            
                            if (data == "[DONE]") {
                                Log.i(TAG, "流式响应完成")
                                break
                            }
                            
                            if (data.isNotEmpty() && data != "{}") {
                                try {
                                    val json = JSONObject(data)
                                    val event = json.optString("event")
                                    
                                    when (event) {
                                        "message" -> {
                                            val answer = json.optString("answer", "")
                                            if (answer.isNotEmpty()) {
                                                fullResponse.append(answer)
                                                withContext(Dispatchers.Main) {
                                                    onResponse(answer)
                                                }
                                            }
                                        }
                                        "message_end" -> {
                                            Log.i(TAG, "消息结束")
                                            break
                                        }
                                        "error" -> {
                                            val errorMsg = json.optString("message", "未知错误")
                                            throw IOException("Dify返回错误: $errorMsg")
                                        }
                                    }
                                } catch (e: Exception) {
                                    Log.w(TAG, "解析响应数据失败: $data", e)
                                }
                            }
                        }
                    }
                } finally {
                    source.close()
                }
                
                val finalResponse = fullResponse.toString()
                Log.i(TAG, "Dify完整响应: $finalResponse")
                
                if (finalResponse.isEmpty()) {
                    withContext(Dispatchers.Main) {
                        onResponse("抱歉，我没有理解您的问题。")
                    }
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "Dify聊天请求失败", e)
            withContext(Dispatchers.Main) {
                val errorMessage = when (e) {
                    is IOException -> "网络连接失败，请检查网络"
                    else -> "处理失败: ${e.message}"
                }
                onResponse(errorMessage)
            }
        }
    }
    
    /**
     * 普通聊天（非流式）
     */
    suspend fun chat(message: String): String = withContext(Dispatchers.IO) {
        try {
            Log.i(TAG, "发送普通消息到Dify: $message")
            
            // 构建请求体
            val requestBody = JSONObject().apply {
                put("query", message)
                put("response_mode", "blocking")
                put("conversation_id", "")
                put("user", "user")
            }.toString()
            
            // 构建请求
            val request = Request.Builder()
                .url("${VoiceConfig.DIFY_BASE_URL}/chat-messages")
                .post(requestBody.toRequestBody("application/json".toMediaType()))
                .addHeader("Authorization", "Bearer ${VoiceConfig.DIFY_API_KEY}")
                .addHeader("Content-Type", "application/json")
                .build()
            
            // 发送请求
            client.newCall(request).execute().use { response ->
                if (!response.isSuccessful) {
                    throw IOException("请求失败: ${response.code}")
                }
                
                val responseBody = response.body?.string() ?: throw IOException("响应体为空")
                val json = JSONObject(responseBody)
                val answer = json.optString("answer", "")
                
                Log.i(TAG, "Dify响应: $answer")
                return@withContext answer.ifEmpty { "抱歉，我没有理解您的问题。" }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "Dify聊天请求失败", e)
            return@withContext when (e) {
                is IOException -> "网络连接失败，请检查网络"
                else -> "处理失败: ${e.message}"
            }
        }
    }
}